/**
 * 定义ui公共模块
 */
(function(window, angular, undefined){

	var module = angular.module('water.common.AJAXService',[]);
	
	module.service('$AJAXService',function($q){
		
		function login(){
			var username = $("#username").val();
			var password = $("#password").val();
			var url = getQueryVariable("url");
			$.post("/op/api/safe/login",{username:username,password:password,url:url},function(result){
			    console.log(result);
			    if(result.result_flag == "ERROR"){
			    	alert(result.result_flag_dsc);
			    	return;
			    }
			    if(result.data && result.data[0].url){
			    	 window.location.href = "http://localhost:8080/op"+result.data[0].url;
			    	 return;
			    }
			    
			    window.location.href = "http://localhost:8080/op/index.html";
				 
			},"json");
		}
		
		
		/**
		 * 
		 */
		this.post = function(url,data,async){
			return this.myPost(getContextPath()+"/api"+url,data,async);
		}
		
		/**
		 * 
		 */
		this.myPost = function(url,data,async,dataType){
			
			var deferred = $q.defer();
			var promise = deferred.promise;
			var isasync = async == null?"true":async;
			var myDataType = dataType == null ?"json":dataType;
			
			if(data instanceof Array){
				data = {data:data};
			}
			
			$.ajax({
				url : url,
				type : 'POST',
				data : data,
				timeout : 35000,
				dataType : myDataType,
				async:isasync,
				beforeSend: function(request) {
                    request.setRequestHeader("TOKEN", "crsfToken");
                },
				success : function(d){
					if(d != null && d.result_flag == 'ERROR'){
						deferred.reject(d.result_flag_dsc);
					}
					else{
						deferred.resolve(d.data);
					}
				}
			});
			return promise;
		}
		
	});
	
}(window, angular));